package server;

import java.io.*;
import java.security.*;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.net.ssl.*;

import server.SiriGuzzoniConn;

public class SiriProxy {
	final static String keystore = "keystore.jks";
	final static int port = 443;
	public static void main(String[] args) {
		SiriGuzzoniConn guzziniConn = new SiriGuzzoniConn();
		try {
			SSLServerSocket s = (SSLServerSocket) getSSLFactory(keystore).createServerSocket(port);
			printDebug("Server started on port: " + port);

			int count = 0;
			while (true) {
				printDebug("Waiting for connection.");
				SSLSocket c = (SSLSocket) s.accept();
				SiriGuzzoniConn.startProxy(c);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SSLServerSocketFactory getSSLFactory(String keystore) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, KeyManagementException, UnrecoverableKeyException{
		char ksPass[] = "1234".toCharArray();
		char ctPass[] = "1234".toCharArray();
		KeyStore ks = KeyStore.getInstance("JKS");
		ks.load(new FileInputStream(keystore), ksPass);
		KeyManagerFactory kmf = 
			KeyManagerFactory.getInstance("SunX509");
		kmf.init(ks, ctPass);
		SSLContext sc = SSLContext.getInstance("TLS");
		sc.init(kmf.getKeyManagers(), null, null);
		SSLServerSocketFactory ssf = sc.getServerSocketFactory();
		return ssf;
	}

	public static void printDebug(String message){
		Date dNow = new Date();
		SimpleDateFormat ft = new SimpleDateFormat("[HH:mm:ss] - ");

		System.out.println(ft.format(dNow) + message);
	}
	public static void printData(String message){
		//             
		System.out.println("" + message);
	}
}